package com.erji.common.mybatis.type;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({String[].class})
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {
    public StringArrayTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, StringUtils.join(parameter, ","));
    }

    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.convertToStringArray(rs.getString(columnName));
    }

    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.convertToStringArray(rs.getString(columnIndex));
    }

    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.convertToStringArray(cs.getString(columnIndex));
    }

    private String[] convertToStringArray(String res) {
        return StringUtils.isBlank(res) ? new String[0] : StringUtils.split(res, ",");
    }
}
